package com.tang.script.extrator;

import com.tang.script.command.AbstractScriptCommand;
import com.tang.script.variable.Variable;
import com.tang.script.variable.VariablesType;

import java.util.Map;

/*
 * {}里面表示的是变量
 * 常量的表示是: {value:type:title}
 * 例如: {field_0:string:用户} 表示从field_0里面取出变量, 类型是stirng, 变量描述是用户
 * */
public class VariablesExtractor {
    private final static VariablesExtractor variablesExtractor = new VariablesExtractor();

    public static VariablesExtractor get() {
        return variablesExtractor;
    }

    public void extracte(AbstractScriptCommand command) {
        String resolvedScriptText = command.getResolvedScriptText();
        Map<String, Variable> variables = command.getVariables();
        StringBuilder stringBuilder = new StringBuilder();
        char[] chars = resolvedScriptText.toCharArray();
        int count = 0;


        for (int i = 0; i < chars.length; i++) {
            while (i < chars.length && chars[i] != '{') {
                stringBuilder.append(chars[i]);
                i++;
            }
            i++;
            StringBuilder temp = new StringBuilder();
            while (i < chars.length && chars[i] != '}') {
                temp.append(chars[i]);
                i++;
            }
            if (temp.length() > 0) {
                int start = temp.length();
                String varName = "var_" + count++;
                Variable variable = resolveVarByString(temp.toString(), varName);
                variables.put(varName, variable);
                stringBuilder.append(varName + " ");
                int end = temp.length();
                variable.setPosition(start, end);
            }
        }
        command.setResolvedScriptText(stringBuilder.toString());
    }

    private Variable resolveVarByString(String string, String varName) {
        String[] split = string.split(":");
        Variable variable = new Variable();
        variable.setType(VariablesType.of(split[1]));
        variable.setValue(split[0]);
        variable.setVarName(varName);
        variable.setTitle(split[2]);
        return variable;
    }
}
